package cn.stronglink.asset.terminal.jd.service;

import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.model.AssetExtMaintenance;
import cn.stronglink.asset.model.ItAssetExtPosition;
import cn.stronglink.asset.model.Preset;
import cn.stronglink.asset.model.PresetDetail;
import cn.stronglink.asset.module.assetmanage.instock.mapper.AssetExtMaintenanceMapper;
import cn.stronglink.asset.module.assetmanage.instock.mapper.PresetDetailMapper;
import cn.stronglink.asset.module.assetmanage.instock.mapper.PresetMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetExtPositionMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetMapper;
import cn.stronglink.asset.terminal.jd.vo.JDDoCheckParam;
import cn.stronglink.asset.terminal.jd.vo.JDResultData;
import cn.stronglink.asset.terminal.jd.vo.JDResultData.DetailData;
import cn.stronglink.asset.terminal.unicom.param.DoCheckParam;
import cn.stronglink.suite.core.util.PropertiesUtil;

@Service
@Transactional(rollbackFor = Exception.class)
public class JDAPIService {
	@Autowired
	private ItassetMapper itassetMapper;
	@Autowired
	private PresetDetailMapper presetDetailMapper;
	@Autowired
	private ItassetExtPositionMapper itassetExtPositionMapper;
	@Autowired
	private PresetMapper presetMapper;
	@Autowired
	private AssetExtMaintenanceMapper maintenanceMapper;

	public DetailData CheckTerminal(List<DoCheckParam> assetList) {
		DetailData detailData = null;
		List<JDDoCheckParam> jdDoCheckParams = new ArrayList<>();
		Map<String, DoCheckParam> doCheckParamMap = new HashMap<>();
		for (DoCheckParam params : assetList) {
			// 同步数据
			JDDoCheckParam param = new JDDoCheckParam();
			param.setSn(params.getSerialNo());
			param.setRfid(params.getRfidNo());
			jdDoCheckParams.add(param);
			doCheckParamMap.put(params.getSerialNo(), params);
		}
		JDResultData jdResultData = null;
		try {
//			String result = "{\"message\":\"\\\"成功\\\"\",\"status_code\":200,\"data\":{\"success\":[\"11111\",\"12345\"],\"fail\":[\"2323\",\"asd\"]}}";
			String result = syncAssetInfoToJD(jdDoCheckParams);
			jdResultData = JSONObject.parseObject(result, JDResultData.class);
			if (jdResultData != null) {
				if (jdResultData.getStatus_code() != 200) {
					return null;
				}
				detailData = jdResultData.getData();
				if (detailData != null) {
					if (detailData.getSuccess() != null && detailData.getSuccess().size() > 0) {
						for (String sn : detailData.getSuccess()) {
							DoCheckParam asset = doCheckParamMap.get(sn);
							if(asset!=null) {
								this.saveData(asset);
							}
						}
					}
//					if (detailData.getFail() != null && detailData.getFail().size() > 0) {
//						data = detailData.getFail();
//						for (String failSn : detailData.getFail()) {
//							failSnStr += failSn + ",";
//						}
//						data = "未找到SN号：" + failSnStr.substring(0, failSnStr.length() - 1);
//					}
				}
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println("同步京东数据异常："+e1.getMessage());
			return null;
		}

		// String jsonParam = JSON.toJSONString(jdDoCheckParams);
		// System.out.println(jsonParam + "同步给jd的数据********");
		// try {
		//// syncAssetInfoToJD(jdDoCheckParams);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		return detailData;
	}

	private void saveData(DoCheckParam asset) {
		// 判断rfid是否存在
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rfidNo", asset.getRfidNo());
		Integer count = itassetMapper.qryAssetByRfidNo(map);
		if (count == 0) {
			PresetDetail detail = presetDetailMapper.qryDetailBySn(asset.getSerialNo());
			// 插入资产表
			if (detail != null) {
				System.out.println("=========准备插入数据");
				asset.setId(IdWorker.getId());
				asset.setStatus(1);
				asset.setIsBorrow(false);
				asset.setIsDistribute(false);
				asset.setIsLight(0);
				asset.setSerialNo(detail.getSerialNo());
				asset.setAssetName(detail.getAssetName());
				asset.setAssetNo(detail.getAssetNo());
				asset.setBrandId(detail.getBrandId());
				asset.setTypeId(detail.getTypeId());
				asset.setModelId(detail.getModelId());
				asset.setCreateBy(asset.getUserId());
				asset.setCreateTime(new Date());
				asset.setPrice(detail.getPrice());
				asset.setRemark(detail.getRemark());
				itassetMapper.insertItAsset(asset);
				System.out.println("=========插入资产表数据完成");

				// 插入资产扩展表
				ItAssetExtPosition posi = new ItAssetExtPosition();
				posi.setId(IdWorker.getId());
				posi.setAssetId(asset.getId());
				posi.setRackId(asset.getRackId());
				posi.setCreateBy(asset.getUserId());
				posi.setCreateTime(new Date());
				posi.setRoomId(detail.getRoomId());
				itassetExtPositionMapper.insertItAssetExtPosition(posi);
				System.out.println("=========插入资产扩产表数据完成");
				// 更新预置详情单为入库
				PresetDetail pd = new PresetDetail();
				pd.setStatus(2);
				pd.setRfidNo(asset.getRfidNo());
				pd.setSerialNo(asset.getSerialNo());
				pd.setId(asset.getPresetDetailId());
				presetDetailMapper.updatePresetDetailBySn(pd);
				System.out.println("=========更新预置详情数据完成");
				Preset p = new Preset();
				p.setId(detail.getPresetId());
				p.setStatus(3);
				presetMapper.updatePreset(p);
				System.out.println("=========更新预置单");
				// 插入资产扩展表
				AssetExtMaintenance mainter = new AssetExtMaintenance();
				mainter.setAssetId(asset.getId());
				mainter.setId(IdWorker.getId());
				mainter.setPrice(detail.getPrice());
				mainter.setContacts(detail.getContacts());
				mainter.setContactsPhone(detail.getContactsPhone());
				mainter.setContractNo(detail.getContractNo());
				mainter.setSupplier(detail.getSupplier());
				mainter.setExpirationTime(asset.getExpirationTime());
				mainter.setBuyTime(asset.getBuyTime());
				mainter.setHotline(asset.getHotline());
				mainter.setInvoiceNo(asset.getInvoiceNo());
				mainter.setCreateBy(asset.getUserId());
				mainter.setCreateTime(new Date());
				maintenanceMapper.insertAssetExtMaintenance(mainter);
				System.out.println("=========插入资产部门表完成");
			}
		}
	}

	private String syncAssetInfoToJD(List<JDDoCheckParam> paramList) throws Exception {
		String msg = "";
		String jsonParam = JSON.toJSONString(paramList);
		System.out.println(jsonParam + "同步给jd的数据：");

		// 第一步：创建HttpClient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 第二步：创建httpPost对象
		String uri = PropertiesUtil.getString("jdCheckUrl");
		System.out.println("同步数据接口：" + uri);
		HttpPost httpPost = new HttpPost(new URI(uri));
		// 第三步：给httpPost设置JSON格式的参数
		StringEntity requestEntity = new StringEntity(jsonParam, "utf-8");
		requestEntity.setContentEncoding("UTF-8");
		httpPost.setHeader("Content-type", "application/json");
		httpPost.setEntity(requestEntity);
		//
		// HttpUriRequest sync = RequestBuilder.post()
		// .setUri(new URI(PropertiesUtil.getString("visitUrl")+"resConfirm"))
		// .addHeader("Content-Type","application/json;charset=utf-8")
		// .addParameter("value", jsonParam)
		// .build();
		CloseableHttpResponse response = httpclient.execute(httpPost);
		HttpEntity result = response.getEntity();
		try {
			msg = EntityUtils.toString(result);
			System.out.println("------------------------同步给jd的数据返回的结果：" + msg);
		} finally {
			response.close();
			httpclient.close();
		}
		return msg;
	}

}
